import ctypes
import struct
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, Factory

lib = ctypes.CDLL("./ext.so");

class echo(Protocol):
	
	def __init__(self):
		self.buffer = '';
		self.fd = -1;

	def dataReceived(self, data):

		self.buffer += data;
		length=len(self.buffer);

		while(length > 0):

			connInfo = struct.pack('i20sP', self.fd, self.transport.getPeer().host, 0);
			ret = lib.handle_input(self.fd, self.buffer, length, connInfo);
			fd, buf, ptr = struct.unpack('i20sP', connInfo);
			print("=====", fd, buf, ptr);
			self.buffer = self.buffer[ret:]

			length=len(self.buffer);
			self.transport.write(data);
			if( ret == 0 ):
				break;		



	def connectionMade(self):
		self.fd = self.transport.fileno();
		lib.handle_open(self.fd);
		print(self);
		pass;
	def connectionLost(self, reason):
		lib.handle_close(self.fd);
		self.fd = -1;
		pass;

class fact(Factory):
	def buildProtocol(self, addr):
		print("a connect in");
		return echo();
		

reactor.listenTCP(1234, fact());
reactor.run();

